﻿ using justice.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace justice.Controllers
{
    [Authorize]
    public class RoleController : Controller
    {
        // GET: Role   角色
        justiceEntities dal = new justiceEntities();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.RoleList = dal.Role.ToList();
            return View();
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult AddRoleView()
        {
            return View();
        }
        public ActionResult AddRole(Role role)
        {
            dal.Role.Add(role);
            if (dal.SaveChanges() > 0)
            {
                return RedirectToAction("Index", "Role");
            }
            return View("AddRoleView");
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult ModRoleView(int id)
        {
            Role role = dal.Role.ToList().Find(l => l.id == id);
            return View(role);
        }
        public ActionResult ModRole(Role role)
        {
            Role _role = dal.Role.ToList().Find(l => l.id == role.id);
            _role.RoleName = role.RoleName;
            if (dal.SaveChanges() > 0)
            {
                return RedirectToAction("Index", "Role");
            }
            return View("ModRoleView");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult DelRole(int id)
        {
            Role role = dal.Role.ToList().Find(l => l.id == id);
            if (role != null)
            {
                //此处一系列处理  外键关系
                List<justice_user> userList = dal.justice_user.ToList().FindAll(l => l.role_id == id);//查有无用户所属此角色
                if (userList.Count > 0)
                {
                    return Json("已有用户所属此角色");
                }
                //无外键关系  直接删除
                dal.Role.Remove(role);
            }
            if (dal.SaveChanges() > 0)
                return Json("成功");
            else
                return Json("服务异常");
        }
    }
}